import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, Tag, Space, Dropdown, Menu, message } from 'antd';
import { PlusOutlined, SearchOutlined, EditOutlined, StopOutlined, DeleteOutlined, EllipsisOutlined, LinkOutlined } from '@ant-design/icons';
import OpenAI from 'openai';
import promptPlusService from '@/services/prompt-plus';

const { Column } = Table;
const { Option } = Select;

const DEFAULT_PAGE_SIZE = 10;


const ModelManagement = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [currentModel, setCurrentModel] = useState<API.Model | null>(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [testing, setTesting] = useState(false);
  const [models, setModels] = useState<API.Model[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    total: 0,
  });
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    loadModels();
  }, [pagination.current, pagination.pageSize, searchText]);

  const loadModels = async () => {
    setLoading(true);
    try {
      const res = await promptPlusService.model.getModels({
        page: pagination.current,
        size: pagination.pageSize,
        keyword: searchText,
      });
      setModels(res);
      setPagination(prev => ({
        ...prev,
        total: res.total,
      }));
    } catch (error) {
      setModels([]);
      console.error('加载模型失败:', error);
      message.error('加载模型失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange = (newPagination: any) => {
    setPagination(newPagination);
  };

  const filteredModels = (models || []).filter(model =>
    model.name?.toLowerCase().includes(searchText.toLowerCase()) ||
    model.identifier?.toLowerCase().includes(searchText.toLowerCase())
  );

  const testConnection = async (record: API.Model) => {
    if (!record.apiKey) {
      message.error('请先设置API密钥');
      return;
    }

    setTesting(true);
    message.loading({ content: `正在测试 ${record.name} 连接...`, key: 'testConnection', duration: 0 });

    try {
      const openai = new OpenAI({
        apiKey: record.apiKey,
        baseURL: record.apiUrl,
        dangerouslyAllowBrowser: true
      });

      let response;
      if (record.identifier === 'GPT4') {
        response = await openai.models.list();
      } else if (record.identifier === 'deepSeek') {
        response = await openai.chat.completions.create({
          model: 'deepseek-chat',
          messages: [{ role: 'user', content: 'Test connection' }],
          max_tokens: 5
        });
      } else {
        response = await openai.completions.create({
          model: 'claude-2',
          prompt: 'Test connection',
          max_tokens: 5
        });
      }

      // Update last tested time via API
      const updatedRecord = await promptPlusService.model.updateModel(record.id, {
        ...record,
        lastTested: new Date().toISOString()
      });

      setModels(prev => prev.map(m => m.id === record.id ? updatedRecord : m));

      message.success({
        content: `${record.name} 连接成功`,
        key: 'testConnection',
        duration: 3
      });
    } catch (error: any) {
      console.error('Connection test failed:', error);
      message.error({
        content: `${record.name} 连接失败: ${error.message}`,
        key: 'testConnection',
        duration: 5
      });
    } finally {
      setTesting(false);
    }
  };

  const showModal = (model: API.Model | null = null) => {
    setCurrentModel(model);
    form.setFieldsValue(model || {
      name: '',
      identifier: '',
      description: '',
      apiUrl: '',
      apiKey: '',
      defaultModel: ''
    });
    setModalVisible(true);
  };

  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields();
    setCurrentModel(null);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const modelData = {
        name: values.name,
        identifier: values.identifier,
        description: values.description,
        apiUrl: values.apiUrl,
        apiKey: values.apiKey,
        defaultSearch: values.defaultModel,
        status: values.status ? values.status : 'Disabled'
      };

      if (currentModel) {
        await promptPlusService.model.updateModel(currentModel.id, modelData);
        message.success('模型更新成功');
      } else {
        await promptPlusService.model.addModel(modelData);
        message.success('模型添加成功');
      }

      setModalVisible(false);
      form.resetFields();
      setCurrentModel(null);
      loadModels();
    } catch (error) {
      console.error('Form submission error:', error);
    }
  };

  const toggleModelStatus = async (record: API.Model) => {
    try {
      await promptPlusService.model.toggleStatus(record.id);
      message.success(`${record.name} 状态已更新`);
      loadModels();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  const deleteModel = async (record: API.Model) => {
    Modal.confirm({
      title: `确认删除 ${record.name}?`,
      onOk: async () => {
        try {
          await promptPlusService.model.deleteModel(record.id);
          message.success('删除成功');
          loadModels();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const actionMenu = (record: API.Model) => (
    <Menu>
      <Menu.Item
        key="test"
        icon={<LinkOutlined />}
        onClick={() => testConnection(record)}
        disabled={testing || record.status === 'Disabled'}
      >
        测试连接 {record.lastTested && `(${new Date(record.lastTested).toLocaleString()})`}
      </Menu.Item>
      <Menu.Item
        key="edit"
        icon={<EditOutlined />}
        onClick={() => showModal(record)}
      >
        编辑
      </Menu.Item>
      <Menu.Item
        key="disable"
        icon={<StopOutlined />}
        onClick={() => toggleModelStatus(record)}
      >
        {record.status === 'Active' ? '禁用' : '启用'}
      </Menu.Item>
      <Menu.Item
        key="delete"
        icon={<DeleteOutlined />}
        onClick={() => deleteModel(record)}
      >
        删除
      </Menu.Item>
    </Menu>
  );

  return (
    <div className="model-management" style={{ padding: 24 }}>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end', gap: 16 }}>
        <Input
          placeholder="搜索模型"
          prefix={<SearchOutlined />}
          style={{ width: 300 }}
          value={searchText}
          onChange={e => {
            setSearchText(e.target.value);
            setPagination(prev => ({ ...prev, current: 1 }));
          }}
          allowClear
        />
        <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
          新增模型
        </Button>
      </div>

      <Table
        dataSource={filteredModels}
        bordered
        loading={loading}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          showQuickJumper: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 条 / 共 ${total} 条`,
        }}
        onChange={handleTableChange}
        rowKey="id"
      >
        <Column title="名称" dataIndex="name" key="name" />
        <Column title="标识" dataIndex="identifier" key="identifier" />
        <Column title="描述" dataIndex="description" key="description" />
        <Column
          title="API地址"
          dataIndex="apiUrl"
          key="apiUrl"
          render={(text) => <a href={`${text}`} target="_blank" rel="noopener noreferrer">{text}</a>}
        />
        <Column title="默认搜索" dataIndex="defaultSearch" key="defaultSearch" />
        <Column
          title="状态"
          dataIndex="status"
          key="status"
          render={(status, record: API.Model) => (
            <Tag color={status === 'Active' ? 'green' : 'red'}>
              {status}
              {record.lastTested && ` (${new Date(record.lastTested).toLocaleDateString()})`}
            </Tag>
          )}
        />
        <Column title="创建时间" dataIndex="createdAt" key="createdAt" />
        <Column
          title="操作"
          key="action"
          render={(_, record: API.Model) => (
            <Dropdown overlay={actionMenu(record)} trigger={['click']}>
              <Button type="text" icon={<EllipsisOutlined />} disabled={testing} />
            </Dropdown>
          )}
        />
      </Table>

      <Modal
        title={currentModel ? "编辑模型" : "新增模型"}
        visible={modalVisible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        okText={currentModel ? "保存" : "确定"}
        cancelText="取消"
        width={600}
        destroyOnClose
        maskClosable={false}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: '请输入模型名称' }]}
          >
            <Input placeholder="例如：DeepSeek" />
          </Form.Item>

          <Form.Item
            name="identifier"
            label="标识"
            rules={[{ required: true, message: '请输入模型唯一标识' }]}
          >
            <Input placeholder="模型唯一标识" disabled={!!currentModel} />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入模型描述" rows={3} />
          </Form.Item>

          <Form.Item
            name="apiUrl"
            label="API地址"
            rules={[{ required: true, message: '请输入API地址' }]}
          >
            <Input placeholder="https://api.deepseek.com/v1" />
          </Form.Item>

          <Form.Item
            name="apiKey"
            label="API密钥"
            rules={[{ required: !currentModel, message: '请输入API密钥' }]}
          >
            <Input.Password
              placeholder={currentModel ? "留空则不修改" : "请输入模型API密钥"}
            />
          </Form.Item>

          <Form.Item
            name="defaultModel"
            label="默认模型"
            rules={[{ required: true, message: '请选择或输入模型名称' }]}
          >
            <Select
              showSearch
              placeholder="输入或选择模型名称"
              optionFilterProp="children"
            >
              <Option value="deepseek-chat">deepseek-chat</Option>
              <Option value="GPT-4 Twin3">GPT-4 Twin3</Option>
              <Option value="Claude & Dijux">Claude & Dijux</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ModelManagement;
